package com.thinkingstar.iads.projectcenter.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.thinkingstar.iads.common.filter.GlobalsFilter;
import com.thinkingstar.iads.common.filter.UserLoginFilter;
import com.thinkingstar.iads.common.jsonUtils.AjaxResult;
import com.thinkingstar.iads.common.utils.DownloadFileUtil;
import com.thinkingstar.iads.common.utils.ExcelPoiUtil;
import com.thinkingstar.iads.common.utils.POIFileUtil;
import com.thinkingstar.iads.common.utils.PictureUtil;
import com.thinkingstar.iads.datacenter.entity.DcProjectMentionInformation;
import com.thinkingstar.iads.datacenter.entity.common.dao.CommonDao;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcFormField;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcProjectMention;
import com.thinkingstar.iads.projectcenter.serviceImpl.ExcelPoiManagerServiceImpl;
/**
 * excel文件操作相关
 * @author Administrator
 *
 */
@IocBean
@At("/projectCenter/excelApi")
@Filters({ @By(type = GlobalsFilter.class) , @By(type = UserLoginFilter.class)})
public class ProjectDesignExcelPoiApi {
	
	
	@Inject
	private DaoDcProjectMention daoDcProjectMention;

	@Inject
	private DaoDcFormField daoDcFormField;
	
	@Inject
	private CommonDao CommonDao;
	
	@Inject
	private ExcelPoiManagerServiceImpl excelPoiManagerServiceImpl;
	
	//导出excel模板通用方法
	@At("/exportExcelModel/?")
	public void exportExcelModel(String mention_data_id , HttpServletRequest req , HttpServletResponse rep) throws IOException{
		DcProjectMentionInformation dcProjectMentionInformation = daoDcProjectMention.fetch(mention_data_id);
		Boolean mention_type = dcProjectMentionInformation.getMention_information_type(); //资料类型
		String table_name = new StringBuffer("dc_mention_").append(dcProjectMentionInformation.getMention_information_code()).toString();
		if(mention_type){//结构化数据表头
			List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);
			String file_name = dcProjectMentionInformation.getMention_information_name()+".xls";
			File excel_file = ExcelPoiUtil.createExcel(file_name, field_list);
			DownloadFileUtil.downLoadFile(excel_file, file_name, req, rep);
		}
	}

	//导出提入资料结构化数据通用方法
	@At("/exportTrzlExcelData/?/?")
	public void exportTrzlExcelData(String mention_data_id ,String project_id, HttpServletRequest req , HttpServletResponse rep) throws IOException{
		DcProjectMentionInformation dcProjectMentionInformation = daoDcProjectMention.fetch(mention_data_id);
		Boolean mention_type = dcProjectMentionInformation.getMention_information_type(); //资料类型
		String table_name = new StringBuffer("dc_mention_").append(dcProjectMentionInformation.getMention_information_code()).toString();
		if(mention_type){//结构化数据表头
			List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);
			QueryResult result =  CommonDao.findDesignCellDataByTableName(new NutMap("project_id",project_id).addv("table_name", table_name));
			List <NutMap> data_list = (List<NutMap>) result.getList();

			String file_name = dcProjectMentionInformation.getMention_information_name()+".xls";
			File file = ExcelPoiUtil.createExcel(file_name, project_id, "提入资料", field_list, data_list);
			DownloadFileUtil.downLoadFile(file, file_name, req, rep);
		}
	}


	//导出excel
	@At("/exportExcelData/?/?")
	public void exportExcelData(String table_name , String project_id,HttpServletRequest req , HttpServletResponse rep){
		List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);//表头
		QueryResult result =  CommonDao.findDesignCellDataByTableName(new NutMap("project_id",project_id).addv("table_name", table_name));
		List <NutMap> data_list = (List<NutMap>) result.getList();
		String file_name = PictureUtil.createFileName("xls");
		//String path = POIFileUtil.getAbFileNameByRepath(POIFileUtil.getExportExcelFileName(file_name));
		try {
			File file = ExcelPoiUtil.createExcel(file_name, project_id, "设计单元", field_list, data_list);
			DownloadFileUtil.downLoadFile(file, file_name, req, rep);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
	}

	//通用上传excel文件方法
	@At("/uploadExcel")
	@Ok("json")
	public Object uploadExcel(@Param("mention_data_id") String mention_data_id , @Param("project_id") String project_id , HttpServletRequest httpServletRequest){
		MultipartFile file=null;
		boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);
		if(isMultipart){
	    	ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) httpServletRequest;
	    	CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
	    	MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest()); 
	    	file=multipartRequest.getFile("file");
	    	InputStream fileStream;
	    	try {
				fileStream = file.getInputStream();
    			String upload_file_name = file.getOriginalFilename();//本地文件名称
    			String suffix_name = upload_file_name.substring(upload_file_name.indexOf(".")+1);//后缀名
    			//String new_file_name = PictureUtil.createFileName(suffix_name);//新文件名
    			String re_file_path = POIFileUtil.getUploadExcelFileName(upload_file_name);
    			String full_file_name = POIFileUtil.getAbFileNameByRepath(re_file_path); //绝对路径
    			Boolean is_success = PictureUtil.storeFile(fileStream, full_file_name);
    			if(is_success){	//上传成功
    				File excel_file = new File(full_file_name);
    				//解析excel
    				DcProjectMentionInformation dcProjectMentionInformation = daoDcProjectMention.fetch(mention_data_id);
    				Boolean mention_type = dcProjectMentionInformation.getMention_information_type(); //资料类型
    				String table_name = new StringBuffer("dc_mention_").append(dcProjectMentionInformation.getMention_information_code()).toString();
    				List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);
    				try {
    					List<Map<Integer, Object>> data_List = ExcelPoiUtil.getDataListByExcel(excel_file);
    					return excelPoiManagerServiceImpl.updateData(data_List, field_list,table_name,project_id);
					} catch (Exception e) {
						e.printStackTrace();
						return AjaxResult.error("excel解析失败,请重新上传!");
					}
    			}
			} catch (IOException e) {
				e.printStackTrace();
				return AjaxResult.error("上传文件不合法!");
			}
		}
		return AjaxResult.error("上传文件不合法!");
	}

}
